package com.jackrain.clouddata.sys.Listenter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.TypeUtils;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.aliyun.openservices.ons.api.impl.util.MsgConvertUtil;
import com.jackrain.clouddata.oms.util.KeyValueUtils;
import com.jackrain.nea.config.PropertiesConf;
import com.jackrain.nea.core.db.Tools;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.tlock.RedisReentrantLock;
import com.jackrain.nea.web.query.QueryEngine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component("com.jackrain.clouddata.sys.Listenter.VIPMessageProcess")
@Slf4j
public class VIPMessageProcess implements MessageProcess {

    @Override
    public void process(Object paramObject, String tag) throws Exception{
        log.info("=======================执行VIP====================");

        JSONArray paramArray = JSONArray.parseArray(JSON.toJSONString(paramObject,new SerializerFeature[]{SerializerFeature.WriteMapNullValue}));
        try {
            if (paramArray != null && paramArray.size() > 0) {
                insertVip(paramArray, tag);
            }
        } catch (Exception e) {
            throw e;
        }
    }

    private void insertVip(JSONArray jsonArray, String tag) {
        //根据tag获取公司ID
        String clientIdSql = "SELECT AD_CLIENT_ID FROM OMS_TAG WHERE ISACTIVE='Y' AND TAGNAME = ?";
        JSONObject clientJson = QueryEngine.getInstance().doQueryObject(clientIdSql, new Object[]{tag});
        if (clientJson == null) {
            throw new NDSException("公司ID未找到!");
        }
        Long clientId = clientJson.getLong("AD_CLIENT_ID");


        JSONArray vipArray = new JSONArray();
        int incount = 0;
        for (int i = 0; i < jsonArray.size(); i++) {
            jsonArray.getJSONObject(i);
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String vipCard = jsonObject.getString("VIPCARD");
            String countSql = "SELECT COUNT(1) FROM C_VIP WHERE AD_CLIENT_ID = ? AND VIPCARD = ?";
            int count = QueryEngine.getInstance().doQueryInt(countSql, new Object[]{clientId, vipCard});
            JSONObject vipJson = JSON.parseObject(JSON.toJSONString(jsonObject, new SerializerFeature[]{SerializerFeature.WriteMapNullValue}), Feature.OrderedField);
            for (int j = 0; j < vipJson.keySet().size(); j++) {
                String key = (String) vipJson.keySet().toArray()[j];
                if (key.contains("DATE")) {
                    vipJson.put(key, TypeUtils.castToDate(jsonObject.get(key)));
                }
            }

            if (count == 0) {
                vipJson.put("AD_CLIENT_ID", clientId);
                vipJson.put("ID", Tools.getSequence("C_VIP"));
                vipArray.set(incount, vipJson);
                incount = incount + 1;
            } else if (count > 0) {
                vipJson.remove("VIPCARD");
                String updateSql = "UPDATE C_VIP SET " + KeyValueUtils.keyUpdateAppend(vipJson.keySet()) + " WHERE AD_CLIENT_ID=? AND VIPCARD=?";
                vipJson.put("AD_CLIENT_ID", clientId);
                vipJson.put("VIPCARD", vipCard);
                QueryEngine.getInstance().executeUpdate(updateSql, vipJson.values().toArray());
            }
        }

        if (vipArray != null && vipArray.size() > 0) {
            StringBuffer insertSql = new StringBuffer();
            insertSql.append("INSERT INTO C_VIP(" + KeyValueUtils.keyAppend(vipArray.getJSONObject(0).keySet()) + ") VALUES(").append(KeyValueUtils.valueAppend(vipArray.getJSONObject(0).size())).append(")");
            QueryEngine.getInstance().executeBatchUpdate(insertSql.toString(), vipArray);
        }
    }

}
